package com.zhuoli.service.schedule.task.timer.task;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @Author: zhuoli
 * @Date: 2018/9/5 20:05
 * @Description:
 */
//@Component
public class ScheduleTask {
    @PostConstruct
    public void startScheduleTask(){
        Timer timer = new Timer();
        //耗时2s左右的任务
        TimerTask task1 = new TimerTask() {
            @Override
            public void run() {
                //获得该任务该次执行的期望开始时间
                System.out.println("expect start time: " + new Date(scheduledExecutionTime()));
                System.out.println("task1 start: " + new Date());
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                }
                System.out.println("task1 end: " + new Date());
            }
        };
        LocalDateTime localDateTime1 = LocalDateTime.now().plusSeconds(-11);
        Date date = Date.from(localDateTime1.atZone(ZoneId.systemDefault()).toInstant());

        System.out.println("now: " + new Date());
        System.out.println("timer start: " + date);
        //设置调度的启动时间为11s前
        timer.schedule(task1, date, 5000);
    }
}
